<template>
	<view class="chat-content">
		<view class="chat-container" @tap.stop="">
			<view class="msg-container">
				<view class="msg-title">
					小星星计划管家
				</view>
				<scroll-view scroll-y="true" :scroll-into-view="`msg${messages.length - 1}`"
					:scroll-with-animation="true">
					<view class="msg-list" :id="`msg${index}`" v-for="(msg, index) in messages" :key="msg.time">
						<view class="msg-item">
							<left-bubble v-if="msg.left" :message="msg.content"></left-bubble>
							<right-bubble v-else :message="msg.content"></right-bubble>
						</view>
					</view>
				</scroll-view>
			</view>
			<!-- <tf-speech-recognizer ref="recognizer" @okClick="recognitionHandler" /> -->
			<enterMsg @sendMessage="sendMessage"></enterMsg>
		</view>
	</view>
</template>
<script setup>
	import {
		apiChat
	} from '@/requestApi/chat';
	import {
		ref,
		inject
	} from 'vue';
	import leftBubble from './leftBubble.vue';
	import rightBubble from './rightBubble.vue';
	import enterMsg from './enterMsg.vue';
	const clearToast = inject("clearToast")
	const messages = ref([]);
	const recognizer = ref();
	const openVoice = () => {
		recognizer.value.show();
	}
	// setTimeout(() => {
	// 	openVoice()
	// }, 1000)
	async function submit() {
		if (input.value === '') return;
		messages.value.push({
			role: "user",
			left: false,
			content: input.value,
			time: new Date().getTime()
		});
		input.value = ""
		postAIMsg();
	}
	const sendMessage = (msg) => {
		if (!msg) return;
		messages.value.push({
			role: "user",
			left: false,
			content: msg,
			time: new Date().getTime()
		});
		postAIMsg();
	}
	// const recognitionHandler = result => {
	// 	console.log('识别结果: ', result);
	// 	if (!result) return;
	// 	messages.value.push({
	// 		role: "user",
	// 		left: false,
	// 		content: result,
	// 		time: new Date().getTime()
	// 	});
	// 	postAIMsg();
	// };
	const postAIMsg = () => {
		apiChat({
			messages: messages.value
		}).then(res => {
			console.log('res', res);
			if (messages.value.length == 20) {
				messages.value = []
			}
			messages.value.push({
				role: "assistant",
				left: true,
				content: res.data.answer || '回答不明确',
				time: new Date().getTime()
			});
		})
	};
</script>
<style lang="scss" scoped>
	.chat-content {
		position: relative;
		width: 100vw;
		height: 100vh;
		background: rgba(0, 0, 0, 0.8);
	}

	.chat-container {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100vw;
		height: calc(100vh - 192rpx);
		background: #ffffff;
		border-radius: 40rpx 40rpx 0px 0px;

		.msg-container {
			padding: 40rpx 10rpx 160rpx 10rpx;
			height: calc(100vh - 240rpx);
			box-sizing: border-box;

			scroll-view {
				height: 100%;
			}
		}

		.msg-title {
			padding-bottom: 5rpx;
			font-size: 32rpx;
			font-weight: 400;
			letter-spacing: 0rpx;
			color: rgba(0, 0, 0, 1);
			text-align: center;
			vertical-align: top;
		}
	}
</style>